﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace CornerBorderDemo
{
    public class CornerBorder : Border
    {
        protected override void OnRender(DrawingContext dc)
        {
            OnApplyChildRender();
            base.OnRender(dc);
        }

        public override UIElement Child
        {
            get => base.Child;
            set
            {
                if (this.Child != value)
                {
                    if (this.Child != null)
                    {
                        this.Child.SetValue(UIElement.ClipProperty, lastClip);
                    }
                    if (value != null)
                    {
                        lastClip = value.ReadLocalValue(UIElement.ClipProperty);
                    }
                    else
                    {
                        lastClip = null;
                    }
                    base.Child = value;
                }

            }
        }

        private RectangleGeometry _clipRect = new RectangleGeometry();
        private object lastClip;

        private void OnApplyChildRender()
        {
            UIElement child = this.Child;
            if (child != null)
            {
                _clipRect.RadiusX = _clipRect.RadiusY = Math.Max(0.0, CornerRadius.TopLeft - (BorderThickness.Left / 2));
                _clipRect.Rect = new Rect(child.RenderSize);
                child.Clip = _clipRect;
            }
        }
    }
}
